package com.azt.front.utils;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.azt.utils.PabankPropertiesUtils;
import org.springframework.stereotype.Component;

//@Component
public class PAMessageListener extends Thread {
	public static Logger logger = LoggerFactory.getLogger("paInfo");
	public static Logger loggerError = LoggerFactory.getLogger("paError");
	List mActiveHandlers = new LinkedList();
	ServerSocket mSocket = null;
	boolean mStopped = false;

	public PAMessageListener() {
		// loggerError.error("创建新的服务器");
		start();
	}

	public void run() {
		try {
			// logger.info("即将创建服务端ServerSocket..");
			createSocket();
			// logger.info("创建服务端ServerSocket成功.");
			while (!mStopped) {
				Socket currentSocket = mSocket.accept();
				logger.info("获得客户端连接");
				// 处理客户端连接
				PAMessageHandler handler = new PAMessageHandler(this, currentSocket);
				mActiveHandlers.add(handler);
				handler.start();
			}
		} catch (Exception e) {
			loggerError.error("创建服务器异常，退出.", e);
			e.printStackTrace();
		}
	}

	/**
	 * 创建server socket
	 */
	public void createSocket() throws Exception {
		// logger.info("创建服务器端 ServerSocket...");
		Exception throwMe = null;
		boolean success = false;
		int portValue = Integer.parseInt(PabankPropertiesUtils.readProperites("frontendBackProt")); // 设定端口号
		try {
			for (int port = 39999; (!success) && port < portValue + 25; port++) {
				mSocket = new ServerSocket(port);
				success = true;
			}

		} catch (Exception e) {
			throwMe = e;
		}

		if (!success)
			throw throwMe;

	}

	/**
	 * 停止服务
	 */
	public void stopServer() {
		mStopped = true;

		try {
			closeServerSocket();
		} catch (Exception e) {
			// ignore--we're stopping.
		}

		Iterator iter = mActiveHandlers.iterator();
		while (iter.hasNext()) {
			((PAMessageHandler) iter.next()).stopHandler();
		}
	}

	/**
	 * 关闭 server socket.
	 */
	void closeServerSocket() throws java.io.IOException {
		if (mSocket != null) {
			mSocket.close();
		}
	}

	public void removeHandler(PAMessageHandler pHandler) {
		mActiveHandlers.remove(pHandler);
	}

	// public static void main(String[] args)
	// {
	// Server server = new Server();
	// }

}
